<?php
namespace Backend\Controllers;

use Models\Vote;
use Models\Wx;
use Models\VoteOption;

class AppvoteController extends BaseController
{
    public function beforeExecuteRoute($dispatcher)
    {
        parent::beforeExecuteRoute($dispatcher);
        $Cuser = $this->Cuser;
        $wxc = Wx::findFirstByuid($Cuser->uid);
        if (!$wxc) {
            $this->flash->warning("<a href='admin/config/wx'>请先点击这里进行微信配置，公共配置->微信配置</a>");
        }
        $this->view->setVar("wxc", $wxc->uid);
    }

    public function indexAction()
    {
        $currentPage = $this->request->getQuery('page');
        $Wx = Wx::findFirstByUid($this->Cuser->uid);
        $token = $Wx->token;
        $votes = Vote::findByToken($token);
        $votesArr=$votes->toArray();
        for($i=0;$i<count($votesArr);++$i)
        {
            $voteoptions=VoteOption::findByVid($votesArr[$i]['id']);
            $voteoptionsArr=$voteoptions->toArray();
            $count=0;

            for($j=0;$j<count($voteoptions);++$j)
            {
              $count+=$voteoptionsArr[$j]['count'];
            }
            $votesArr[$i]['count']=$count;

        }
      //  $voteoption=VoteOption::findByVid($vote)
        $paginator = new \Phalcon\Paginator\Adapter\NativeArray(array(
            "data" => $votesArr,
            "limit" => 10,
            "page" => $currentPage,
        ));
        $this->view->page = $paginator->getPaginate();

        $host = $this->config->host;
        $voteListUrl = $host . '/frontend/vote/index' . '?token=' . $token;
        $this->view->setVar('voteListUrl', $voteListUrl);


    }

    public function  createAction()
    {
        if($post=$this->request->getPost()) {
           //postArr=$post;
            if(!$post['order'])
            {
                $this->flash->warning("请输入选项");
            }
            else
            {
                //------post work--------------//
                $name = $this->request->getPost("name");
                $pic = $this->request->getPost("pic");
                $time_end = $this->request->getPost("time_end");
                $type = $this->request->getPost("type");
                $state = $this->request->getPost("state");
                $detail=$this->request->getPost("detail");
                $Wx = Wx::findFirstByUid($this->Cuser->uid);
                $token = $Wx->token;
                if (!$name || !$time_end || !$pic || !$type || !$state||!$detail) return $this->flash->warning("请输入完整");
                $vote = Vote::findFirst("name='".$name."' AND token='".$token."'");
                if (!$vote) {
                    $myvote = new Vote();
                    $myvote->name = $name;
                    $myvote->pic = $pic;
                    $myvote->time_start = date("Y-m-d");
                    $myvote->time_end = $time_end;
                    $myvote->token = $token;
                    $myvote->type=$type;
                    $myvote->state=$state;
                    $myvote->detail=$detail;
                    $myvote->create();
                } else return $this->flash-> warning("该投票已存在");


                //----------update voteOption's data-----------//
                for ($i = 0; $i < count($post['order']); ++$i) {
//                    if($post['option_name'][$i]="")return $this->flash->warning("请输入选项");
                    $option = new VoteOption();
                    $option->option = $post['option_name'][$i];
                    $option->order = $post['order'][$i];
                    $option->detail=$post['option_detail'][$i];
                    $option->count=0;
                    $votefind = Vote::findFirst("name='".$name."' AND token='".$token."'");
                    $option->vid = $votefind->id;
                    $option->pic = $post['option_pic'][$i];
                    $option->create();
                }
                $this->flash->warning("投票创建成功");
            }

        }
    }

    public function updateAction()
    {

        $id=$this->request->get('id');
        $token=$this->request->get('token');
        $vote1=Vote::findFirst($id);
        if($token!=$vote1->token)
        {
            return $this->flash->warning("您没有权限访问该投票");
        }
        else
        {
            //----------------set data to view---------------//
            $this->view->setVar('vote',$vote1);
            $voteOptions=VoteOption::findByVid($vote1->id);
            $this->view->setVar('voteOptions',$voteOptions);
            $voteCount=count($voteOptions);
            $this->view->setVar("voteCount",$voteCount);


            //------post work--------------//
             if($post=$this->request->getPost())
            {
                if(!$post['order'])
                {
                    $this->flash->warning("请输入选项");
                }
                else
                {

                    //------------- update vote's data-------------//
                    $name = $this->request->getPost("name");
                    $pic = $this->request->getPost("pic");
                    $time_end = $this->request->getPost("time_end");
                    $detail = $this->request->getPost("detail");
                    $type = $this->request->getPost("type");
                    $state = $this->request->getPost("state");

                    if (!$name || !$time_end || !$pic || !$type || !$state) return $this->flash->warning("请输入完整");
                    else {
                        $vote1->name = $name;
                        $vote1->pic = $pic;
                        $vote1->time_start = date("Y-m-d");
                        $vote1->time_end = $time_end;
                        $vote1->type = $type;
                        $vote1->state = $state;
                        $vote1->token = $token;
                        $vote1->detail=$detail;
                        $vote1->save();
                    }
                    //----------update voteOption's data-----------//
                    for ($i = 0; $i < count($post['order']); ++$i)
                    {
//                        if($post['option_name'][$i]="")return $this->flash->warning("请输入选项");
                        if($post['idNum'][$i]) {
                            $optionFind = VoteOption::findFirstById($post['idNum'][$i]);
                        }
                        else{
                            $optionFind=null;
                        }
                        if(!$optionFind) {
                            $option = new VoteOption();
                            $option->option = $post['option_name'][$i];
                            $option->order = $post['order'][$i];
                            $option->detail=$post['option_detail'][$i];
                            $option->count = 0;
                            $votefind =Vote::findFirst("name='".$name."' AND token='".$token."'");
                            $option->vid = $votefind->id;
                            $option->pic = $post['option_pic'][$i];
                            $option->create();
                        }
                        else{
                            $optionFind->option = $post['option_name'][$i];
                            $optionFind->order = $post['order'][$i];
                            $optionFind->detail=$post['option_detail'][$i];
                            $optionFind->pic= $post['option_pic'][$i];
                            $optionFind->update();
                        }

                    }
                    $this->flash->warning("修改成功");
                    return $this->response->redirect("admin/appvote/update/?token=$token&id=$id");

                }
            }
        }


    }


    public function  detailAction()
    {
        $token=$this->request->get('token');
        $id=$this->request->get('id');
        $vote=Vote::findFirstById($id);
        if($vote->token!=$token)
        {
            return $this->flash->warning('你没有权限访问该页面');
        }
        else
        {
            $host = $this->config->host;
            $voteUrl = $host . '/frontend/vote/detail' . '?token=' . $token . "&id=" . $id . "&openid=88888";
            $this->view->setVar('voteUrl', $voteUrl);
            $this->view->setVar('vote',$vote);
            $voteoptions=VoteOption::findByVid($id);
            $this->view->setVar('voteoptions',$voteoptions);
        }
    }



    public function deleteAction($id)
    {
        $this->view->disable();
        $vote=Vote::findFirstById($id);
        if(!$vote)
        {
            $status='error';
        }
        else{
            $vote_options=VoteOption::findByVid($id);
            $vote_options->delete();
            $vote->delete();
            $status='success';
        }
        return json_encode(array('status'=>$status));
    }

    public function deleteoptionAction($id)
    {
        $this->view->disable();
        $voteoption=VoteOption::findFirstById($id);
        if(!$voteoption)
        {
            $status='error';
        }
        else{

            $voteoption->delete();

            $status='success';
        }
        return json_encode(array('status'=>$status));
    }

    public function dashboardAction()
    {

    }
}
